package edu.ustb.efws.controller;

import edu.ustb.efws.base.domain.User;
import edu.ustb.efws.base.service.UserService;
import edu.ustb.efws.controller.form.AccountForm;
import edu.ustb.efws.controller.form.UpdatePasswordForm;
import edu.ustb.efws.controller.vo.OkVo;
import edu.ustb.efws.controller.vo.ResultVo;
import edu.ustb.efws.security.Credential;
import edu.ustb.efws.security.CredentialContextUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 账户管理
 *
 * @author TS Group
 */
@RestController
@RequestMapping("/account")
@Api(value = "/account", tags = "账户管理")
public class AccountController {
    private final UserService service;

    @Autowired
    public AccountController(UserService service) {
        this.service = service;
    }

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("获取账户信息")
    public ResultVo<User> get(){
        Credential credential = CredentialContextUtils.getCredential();
        return ResultVo.success(service.get(credential.getId()));
    }

    @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("修改账户信息")
    public ResultVo<User> update(@Valid @RequestBody AccountForm form){

        Credential credential = CredentialContextUtils.getCredential();
        User user = service.get(credential.getId());
        user.setName(form.getName());
        user.setTel(form.getTel());
        return ResultVo.success(service.update(user));
    }

    @PutMapping(value = "updatePassword", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("修改密码")
    public ResultVo<OkVo> updatePassword(@Valid @RequestBody UpdatePasswordForm form){
        Credential credential = CredentialContextUtils.getCredential();
        boolean ok = service.updatePassword(credential.getId(), form.getPassword(), form.getNewPassword());
        return ResultVo.success(new OkVo(ok));
    }
}
